Explain the main and init function in Go Programming Language | Go Programming Tutorial
In this article, you will learn the two main concepts of Go Programming:
- What is the main() function in GoLang?
- What is the init() function in GoLang?
In Go Programming, the functionality of the two functions is reversed for the special purpose and the functions are main() and init() functions.
What is the main() function in GoLang?
The main package is a special package in goLang which is used only with the programs that are executable and this package contains main() functions. The main() function is a particular type of function and it is the entry point of the executable programs. It does not take any arguments nor return anything. GoLang automatically calls the main functions, so there is no need to make a call explicitly. It is important to have the main function. Every executable program must have a single main package and main() function.
What is the init() function in GoLang?
init() function is similar to the main function that means just like the main() function, init() also does not take arguments nor return anything. init() function is available in every package and this function is called when the package is declared. This function is declared implicitly, you cannot reference it from anywhere. The user is allowed to create multiple init() functions in the same program and they execute in the same order they are created. The user can create the init() function anywhere in the program and they are called in lexical file name order. The init() function always executes before the execution main() function. Hence, it does not depend on the main() function. The fundamental purpose of init() is to initialize the global variables that can not be initialized in the global context.


